<?php
namespace Poi\EttsBundle\Model;

/**
 * @author Ricardo J. Vazquez
 * 
 * Collection of Vehicle models
 */
class Vehicles extends Collection
{
	public function init() {	
	}
	
	/**
	* Loads the collection with Vehicle models
	*
	* @param $col 
	*/
	public function loadVehicles(Collection $col){
		$sql = "SELECT
			V1.VIN,
			V1.Owner,
			V1.Expiration,
			V1.VehicleTag,
			V1.LoadCapacity,
			V1.HorsePower,
			V1.Doors,
			C1.Color,
			M2.Model,
			M2.Brand,
			V1.Year,
			V1.RegisterDate,
			V1.Description,
			V1.LicensePlate,
			V1.Address,
			V1.RfidKey
		FROM Vehicle V1
			INNER JOIN Colors C1 ON V1.Color = C1.idColors
			INNER JOIN (
				SELECT 
					M1.idModel, 
					M1.Model, 
					B1.Brand 
				FROM Model M1 
					INNER JOIN Brand B1 ON M1.Brand = B1.idBrand
				) M2 ON V1.Model = M2.idModel";
				
		$loadStmt = $this->conn->prepare($sql);

		$loadStmt->execute();

		$vehicles = $loadStmt->getWrappedStatement()->fetchAll(
			\PDO::FETCH_CLASS, 
			"Poi\\EttsBundle\\Model\\Vehicle", 
			array($this->conn)
		);

		$count = 0;
		foreach($vehicles as $vehicle){
			$vehicle->setLoaded(true);
			$this->addItem($vehicle, $count++);
		}
	}
	
	public function toXML(\SimpleXMLElement &$xml=null){
		$return = false;
		if(is_null($xml)){
			$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><xmlresponse></xmlresponse>');
			$return = true;
		}
		
		$length = $this->length();
		
		$vehiclesXML = $xml->addChild('vehicles');
		
		for($i = 0; $i < $length; $i++)
		{
			$this->getItem($i)->toXML($vehiclesXML);
		}
				
		if($return){		
			return $xml->asXML();
		}
	}
	
}